/**
 * @file: IndividualInsert.java
 *
 * @author: 蒋振
 *
 * @date: 2016年4月11日 下午6:14:37
 *
 * @copyright: 南京凯盛
 */
package cn.com.kisen.db.mongo;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;


/**
 * 
 *
 * @author 蒋振
 * @version 1.0 Created on 2016年4月11日 下午6:14:37
 */
public class IndividualInsert {
    
    private int pts =10000;

    private IndividualInsert(){}
    
    private static IndividualInsert instance = new IndividualInsert();
    
    private static Logger logger = Logger.getLogger(IndividualInsert.class);
    
    /**
     * 插入1秒内的采样数据
     * 
     * @param collection
     * @param sec
     * @author: 蒋振
     * @date: Created on 2016年4月11日 下午2:56:15
     */
    private void batchInsertOneSec(MongoDatabase mongoDatabase,Date date){
        
        for(Integer tagID =0;tagID<pts;tagID++){
            MongoCollection<Document> collection = mongoDatabase.getCollection(tagID.toString());
            Document document = new Document("_id",date).
                    append("value", date.getTime()/1000000);
            collection.insertOne(document);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
        logger.info(sdf.format(date) + " fininshed" );       // 取秒数
    }
    
    public static IndividualInsert getInstance(){
        return instance;
    }
    
    public void batchInsertOneDay(){
        
        // 获得MongoDB客户端
        MongoClient     mongoClient = new MongoClient("localhost",27017);
        // 获得数据库 - "sample2"
        MongoDatabase   mongoDatabase = mongoClient.getDatabase("sample2");
        // 创建10000个tag集合
        logger.info("creating tags");
        for(Integer tagID = 0;tagID<pts;tagID++){
            mongoDatabase.createCollection(tagID.toString());
        }
        logger.info("created");
        logger.info("sampling");
        long nowSec = new Date().getTime()/1000;
        long now = 1000 * nowSec;
        for(int i=0;i<20*60;i++){
            Date nexSec = new Date(now+1000*i);
            batchInsertOneSec(mongoDatabase,nexSec);
        }
        logger.info("sampled");
        // 关闭MongoDB客户端
        mongoClient.close();
    }

}
